<?php

class My_Controller_FrontendAction extends My_Controller_Action
{
	public function init()
	{
		parent::init();
		
		$this->_updateSession();
		
		$this->view->vote = Vote::getCurrentVote();
		$this->view->ads = Ads::getCurrentAds();
		$this->view->topmenu = Menuitem::getItems(Menuitem::MENU_TOP);
		$this->view->areasmenu = Menuitem::getItems(Menuitem::MENU_AREAS);
		$this->view->bottomleftmenu = Menuitem::getItems(Menuitem::MENU_BOTTOMLEFT);
		$this->view->bottomrightmenu = Menuitem::getItems(Menuitem::MENU_BOTTOMRIGHT);
		$this->view->logomenu = Logo::getLatestLogos();
		$this->view->blogmenu = Blog::getLatestBlogs();
		$this->view->latestVideo = Video::getLatestVideo();
	}
	
	private function _updateSession()
	{
		// Clean up old sessions
		Doctrine_Query::create()
				->delete('Session')
				->where('updated < ?', date("Y-m-d H:i:s", time()-10*60)) // 10 minutes
				->execute();
				
				
		$visit = Doctrine::getTable('Statistic')->findBySql('name = ?', 'NUM_VISIT')->getFirst();
		$click = Doctrine::getTable('Statistic')->findBySql('name = ?', 'NUM_CLICK')->getFirst();
		if (!$visit) {
			$visit = new Statistic();
			$visit['name'] = 'NUM_VISIT';
			$visit['value'] = 0;
			$visit->save();
		}
		if (!$click) {
			$click = new Statistic();
			$click['name'] = 'NUM_CLICK';
			$click['value'] = 0;
			$click->save();
		}
		
		$click['value'] = $click['value'] + 1;
		$click->save();
		
			$session = Doctrine::getTable('Session')->findBySql("(ipaddress = ?) AND (sessionid = ?)", Array($_SERVER['REMOTE_ADDR'], session_id()))->getFirst();
		
		if ($session) {
			// Old session
			$session->save();
		} else {
			// New session
			$session = new Session();
			$session->ipaddress = $_SERVER['REMOTE_ADDR'];
			$session->sessionid = session_id();
			$session->save();
			
			$visit['value'] = $visit['value'] + 1;
			$visit->save();
		}
		
		$stat = Array(
			'click' => $click['value'],
			'visit' => $visit['value']
		);
		
		$this->view->statistic = $stat;
	}
}
